<?php
namespace App\Factory\Refund;

use App\Factory\Wechat\Factory as WechatFactory;
use App\Utils\Other\Sandpay\Refund\Mini;
use EasyWeChat\Kernel\HttpClient\HttpClientMethods;
use function Hyperf\Config\config;
use function Hyperf\Support\make;

Class Factory {

    /**
     * 衫德微信小程序退款
     * @param array $params
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sandpayMini(array $params):array
    {
        /** @var Mini $miniPay */
        $miniPay = make(Mini::class);

        $data = [
            'orderCode' => $params['out_refund_no'],
            'oriOrderCode' => $params['out_trade_no'],
            'refundReason' => $params['reason'],
            'refundAmount' => str_pad($params['amount'] * 100, 12, '0', STR_PAD_LEFT)
        ];

        return $miniPay->handle($data);
    }

    /**
     * 微信退款
     * @param array $params
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Pay\Exceptions\InvalidSignatureException
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function wechatMini(array $params)
    {
        /** @var WechatFactory $pay */
        $pay = make(WechatFactory::class);
        $app = $pay->pay();

        /** @var HttpClientMethods $client */
        $client = $app->getClient();

        $params['notify_url'] = getDomain()."/school/v1/refund/notify/wechatMini";
        $params['amount'] = [
            'refund' => $params['amount'] * 100,
            'total' => $params['total'] * 100,
            'currency' => 'CNY'
        ];

        $response = $client->postJson('v3/refund/domestic/refunds', $params);
        $app->getValidator()->validate($response->toPsrResponse());

        return [$params, $response, $params];
    }

}